import React, { useState, useEffect } from 'react';
import axios from 'axios';
import DataTable from 'react-data-table-component';
import { Dialog, DialogTitle, DialogContent, Button } from '@mui/material';
import AddSensorDataDialog from './AddSensorDataDialog';
import "./Feeding.css"
import {paginationComponentOptions, customTableStyles} from '../Constants'
import { useNavigate } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faArrowLeft } from '@fortawesome/free-solid-svg-icons';


const SensorDataPage = () => {
    const [sensorData, setSensorData] = useState([]);
    const [openDialog, setOpenDialog] = useState(false);
    const [sensorFilter, setSensorFilter] = useState("");
    const [equipmentFilter, setequipmentFilter] = useState("")
    const [sensors, setSensors] = useState([]);
    const [equipments, setEquipments] = useState([]);

    useEffect(() => {
        fetchData();
        fetchEquipments()
    }, []);

    useEffect(() => {
        fetchSensors();
        if(equipmentFilter === ""){
            setSensors([])
            setSensorFilter("")
            fetchData()
        }
    }, [equipmentFilter]);

    const fetchData = async () => {
        try {
            setSensorData([])
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/indication${sensorFilter!== ""? "?sensor="+sensorFilter:""}`, {headers});
            setSensorData(response.data.indications)
        } catch (error) {
            console.error('Error fetching data:', error);
        }
    };

    const fetchSensors = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/sensors?equipment=${equipmentFilter}`, {headers});
            setSensors(response.data.sensors);
        } catch (error) {
            console.error('Error fetching sensors:', error);
        }
    };
    const fetchEquipments = async () => {
        try {
            const headers = {
                'Authorization': `Bearer ${localStorage.getItem('access')}`,
            };
            const response = await axios.get(`${process.env.REACT_APP_API_BASE_URL}/equipment`, {headers});
            setEquipments(response.data.equipments);
        } catch (error) {
            console.error('Error fetching уйгшзьутеы:', error);
        }
    };

    const handleOpenDialog = () => {
        setOpenDialog(true);
    };

    const handleCloseDialog = () => {
        setOpenDialog(false);
    };

    const handleSensorChange = (event) => {
        setSensorFilter(event.target.value)
    }
    const handleEquipmentChange = (event) => {
        setequipmentFilter(event.target.value)
    }
    useEffect(() => {
        fetchData()
    }, [sensorFilter])

    const columns = [
        { name: 'Значение', selector: row => row.value },
        { name: 'Дата и время', selector: row => new Date(row.date_time).toLocaleString() },
        { name: 'Датчик', selector: row => row.name},
        { name: 'Оборудование', selector: row => row.ename},
        { name: 'Кем внесено', selector: row => row.last_name + " " + row.first_name},
        { name: 'Комментарий', selector: row => row.comment},
    ];
    const navigate = useNavigate();

  const goBack = () => {
    navigate('/home')
  };

    return (
        <div style={{ padding: 30 }}>
            <button onClick={goBack}>
        <FontAwesomeIcon icon={faArrowLeft} /> Главное меню
      </button>
            <div className="header">
                <div className="left">
                    <h1 style={{ paddingLeft: '20px', fontWeight: 'normal' }}>Показатели датчиков</h1>
                </div>
                <div className="right">
                    <button onClick={handleOpenDialog}>Добавить новые данные</button>
                </div>
            </div>
            
            <select
                value={equipmentFilter}
                onChange={handleEquipmentChange}
                style={{margin: 0, width: '100%', marginRight: 10, paddingBlock: 5 }}
            >
                <option value="">Выберите оборудование</option>
                {equipments.map(eqr => (
                    <option key={eqr.eid} value={eqr.eid}>{eqr.ename}</option>
                ))}
            </select>
            <select
                value={sensorFilter}
                onChange={handleSensorChange}
                style={{margin: 0, width: '100%', marginRight: 10, paddingBlock: 5 }}
            >
                <option value="">Выберите датчик</option>
                {sensors.map(eqr => (
                    <option key={eqr.id} value={eqr.id}>{eqr.name}</option>
                ))}
            </select>
            <DataTable
                columns={columns}
                data={sensorData}
                pagination
                defaultSortFieldId={1}
                paginationComponentOptions={paginationComponentOptions}
                customStyles={customTableStyles}
            />
            <AddSensorDataDialog open={openDialog} onClose={handleCloseDialog} fetchData={fetchData} />
        </div>
    );
};

export default SensorDataPage;
